package dao;

import bean.Position;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.query.Query;
import java.util.List;

public class TPositionDAOImpl implements PositionDAO {
    private Session session;
    private Transaction transaction;
    private boolean completed;

    public TPositionDAOImpl(Session session) {
        this.session = session;
    }

    @Override
    public boolean add(Position position) {
        try {
            transaction = session.beginTransaction();
            session.save(position);
            completed = true;
        } catch (Exception e) {
            completed = false;
            e.printStackTrace();
        } finally {
            transaction.commit();
        }
        return completed;
    }

    @Override
    public boolean edit(Position temporary) {
        try {
            transaction = session.beginTransaction();
            Position position = session.get(Position.class, temporary.getPositionId());
            position.setPositionName(temporary.getPositionName());
            session.save(position);
            completed = true;
        } catch (Exception e) {
            completed = false;
            e.printStackTrace();
        } finally {
            transaction.commit();
        }
        return completed;
    }

    @Override
    public boolean remove(int positionId) {
        try {
            transaction = session.beginTransaction();
            Position position = session.get(Position.class, positionId);
            session.delete(position);
            completed = true;
        } catch (Exception e) {
            completed = false;
            e.printStackTrace();
        } finally {
            transaction.commit();
        }
        return completed;
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<Position> queryAll() {
        List<Position> positions = null;
        try {
            Query<Position> query = session.createQuery("FROM Position");
            positions = query.list();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return positions;
    }

    @Override
    public Position query(int positionId) {
        Position position = null;
        try {
            @SuppressWarnings("unchecked")
            Query<Position> query = session.createQuery("FROM Position WHERE positionId=" + positionId);
            position = query.list().get(0);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return position;
    }
}
